// Populate the database 
//
function populateDB(tx) {
    tx.executeSql('DROP TABLE IF EXISTS DICTIONARYSOURCE');
    tx.executeSql('DROP TABLE IF EXISTS DICTIONARYTARGET');
   
    tx.executeSql('CREATE TABLE IF NOT EXISTS DICTIONARYTARGET (id unique, targetWord, detailedEntry)');
    tx.executeSql('INSERT INTO DICTIONARYTARGET (id, targetWord, detailedEntry) VALUES(1, "riwurrujun", "She is telling lies")');
    tx.executeSql('INSERT INTO DICTIONARYTARGET (id, targetWord, detailedEntry) VALUES(2, "balarrakan", "She is telling truth")');
    
    tx.executeSql('CREATE TABLE IF NOT EXISTS DICTIONARYSOURCE (id unique, dictionaryTarget_id, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, FOREIGN KEY (dictionaryTarget_id) REFERENCES DICTIONARYTARGET(id))');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTarget_id, sourceWord, partOfSpeech, inflection, disambiguation, targetWord) VALUES (1, 2, "foot", "n.", "his/her/its foot", "on stomach", "balarrakanSource")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTarget_id, sourceWord, partOfSpeech, inflection, disambiguation, targetWord) VALUES (2, 1, "head", "n.", "his/her/its foot", "on stomach",  "riwurrujun")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTarget_id, sourceWord, partOfSpeech, inflection, disambiguation, targetWord) VALUES (3, 2, "hand", "n.", "his/her/its foot", "on stomach", "balarrakan")');
    
}

// Query the database
//
function queryDB(tx) {
    tx.executeSql('SELECT * FROM DICTIONARYSOURCE AS s, DICTIONARYTARGET AS t WHERE s.dictionaryTarget_id = t.id', [], querySuccess, errorCB);
}

// Query the success callback
//
function querySuccess(tx, results) {
    var len = results.rows.length;
    console.log("DEMO table: " + len + " rows found.");
    for (var i=0; i<len; i++){
        console.log("Row = " + i + " ID = " + results.rows.item(i).targetWord + " Data =  " + results.rows.item(i).sourceWord);
    }
}

// Transaction error callback
//
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

// Transaction success callback
//
function successCB() {
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(queryDB, errorCB);
}

// PhoneGap is ready
//
function onDeviceReady() {
    //playAudio("audio/y1.mp3");
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
    
    
}



// Audio player
//
var my_media = null;
var mediaTimer = null;

// Play audio
//
function playAudio(src) {

	
    if (my_media == null) {
        // Create Media object from src
        my_media = new Media(src, onSuccess, onError);
        
    } // else play current audio
    // Play audio
    my_media.play();

    // Update my_media position every second
    if (mediaTimer == null) {
        mediaTimer = setInterval(function() {
            // get my_media position
            my_media.getCurrentPosition(
                // success callback
                function(position) {
                    if (position > -1) {
                        setAudioPosition((position) + " sec");
                    }
                },
                // error callback
                function(e) {
                    console.log("Error getting pos=" + e);
                    setAudioPosition("Error: " + e);
                }
            );
        }, 1000);
    }
}


// onSuccess Callback
//
function onSuccess() {
    console.log("playAudio():Audio Success");
}

// onError Callback 
//
function onError(error) {
    alert('code: '    + error.code    + '\n' + 
          'message: ' + error.message + '\n');
}


//<debug>
Ext.Loader.setPath({
    'Ext': 'sdk/src',
    'Sencha': 'app',
    'Sqlite': 'sqlite'
});
//</debug>

Ext.require('Sencha.util.InitSQLite');





Ext.application({
    // Rename this
    name: 'Sencha',
   

     

    // Not sure if it is best practice to have all these here?
    controllers: ['DictionarySourceController'],
    views: ['Main','TabView','DictionaryTargetDetailView', 'DictionarySourceListView', 'DictionarySourceNavigationView', 'DictionaryFormView', 'PhraseListView'],
    stores: ['DictionarySources','DictionarySourcesOffline', 'DictionaryTargets', 'Phrases'],
    models: ['DictionarySource', 'DictionaryTarget', 'Phrase'],
    
    onReady: function() {
    	onDeviceReady();
    	Sencha.util.InitSQLite.initDb();
    },
                    
    init: function() {

    	
    },            
    
    launch: function() {
      
        Ext.Viewport.add({
            xtype: 'mainpanel'
        });
    },
    
    onUpdated: function() {
        Ext.Msg.confirm(
            "Application Update",
            "This application has just successfully been updated to the latest version. Reload now?",
            function() {
                window.location.reload();
            }
        );
    }
    
});